package com.ljq.cksp.controller;

import com.ljq.cksp.dao.BookDao;
import com.ljq.cksp.dao.DocumentDao;
import com.ljq.cksp.dao.LawDao;
import com.ljq.cksp.dao.UserDAO;
import com.ljq.cksp.pojo.*;
import com.ljq.cksp.service.BookService;
import com.ljq.cksp.service.DocumentService;
import com.ljq.cksp.service.LawService;
import com.ljq.cksp.service.UserService;
import com.ljq.cksp.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * @Author:ljq
 * @Date:2020/4/17
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    UserService userService;
    @Autowired
    BookService bookService;
    @Autowired
    LawService lawService;
    @Autowired
    DocumentService documentService;

    @GetMapping("/user")
    public Result listUser(@RequestParam(value="start", defaultValue="0") int start, @RequestParam(value="size", defaultValue="10") int size) {
        return new Result(userService.listUser(start, size));
    }

    @DeleteMapping("/user/{userId}")
    public Result deleteUser(@PathVariable("userId")int userId) {
        userService.delete(userId);
        return new Result();
    }

    @PostMapping("/admin")
    public Result addAdmin(User user) {
        userService.addAdmin(user);
        return new Result();
    }

    @PostMapping("/law")
    public Result uploadLaw(HttpServletRequest req, @RequestParam("file")MultipartFile file){
        try{
            String fileName = file.getOriginalFilename();
            String destFileName = req.getServletContext().getRealPath("")+"uploaded"+ File.separator+fileName;
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            file.transferTo(destFile);
            bookService.saveFromFile(destFile);
            lawService.saveFromFile(destFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }

    @PostMapping("/document")
    public Result uploadDocument(HttpServletRequest req, @RequestParam("file")MultipartFile file){
        try{
            String fileName = file.getOriginalFilename();
            String destFileName = req.getServletContext().getRealPath("")+"uploaded"+ File.separator+fileName;
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            file.transferTo(destFile);
            documentService.saveFromFile(destFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }
}
